package org.richin.dao.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;

import javax.sql.DataSource;

import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

public class DBUtil  {
	protected final static Log logger = LogFactory.getLog(DBUtil.class);

	/**
	 * 获取数据库连接
	 * 
	 * @param driver
	 * @param url
	 * @param username
	 * @param password
	 * @return
	 */
	public static Connection getConnection(String driver, String url, String username, String password) {
		logger.info("获取数据库连接!");
		Connection conn = null;
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException connectionException) {
			System.out.println(connectionException.getMessage());
		}
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException connectionException) {
			System.out.println(connectionException.getMessage());
			logger.error("获取数据库失败!" + connectionException.getStackTrace());
		}
		return conn;
	}

	/**
	 * Creates and returns the pooling data source.
	 * @param aJdbcUrl
	 * @param aUsername
	 * @param aPassword
	 * @return
	 */
	public static DataSource createDataSource(String aJdbcUrl, 
			String aJdbcDriver, String aUsername, String aPassword) 
	throws SQLException {
		GenericObjectPool objectPool;
		DriverManagerConnectionFactory connectionFactory;
		PoolableConnectionFactory poolableConnectionFactory;
		PoolingDataSource dataSource;
		
		if (DbUtils.loadDriver(aJdbcDriver)) {
			objectPool = new GenericObjectPool(null);
			connectionFactory = new DriverManagerConnectionFactory(aJdbcUrl,
					aUsername, aPassword);
			poolableConnectionFactory = new PoolableConnectionFactory(
					connectionFactory, objectPool, null, null, false, false);
			dataSource = new PoolingDataSource(objectPool);
			
		} else {
			throw new SQLException("Unable to load driver: [" + 
					aJdbcDriver + "]");
		}
		return dataSource;
	}
    /**
     * Executes an SQL string on the specified connection.
     */
    public static void execute(String sql, Connection conn) throws SQLException {

        Statement statement = conn.createStatement();
        statement.executeUpdate(sql);
    }
    /**
     * Reads an SQL script from the specified input stream and executes it on
     * the specified connection. The script must have the following form:<br>
     * &lt;statement1&gt;;&lt;newline&gt;<br>
     * &lt;statement2&gt;;&lt;newline&gt;<br>
     * ...<br>
     * &lt;statementN&gt;;<br>
     * where statementXXX is a (possibly multi-lined) SQL statement.
     */
    public static void executeScript(InputStream script, Connection conn)
            throws IOException, SQLException {

        BufferedReader in = new BufferedReader(new InputStreamReader(script));

        StringBuffer sql = new StringBuffer();

        String line;
        while ((line = in.readLine()) != null) {
            int pos = line.indexOf(";");
            if (pos == -1) {
                sql.append(line);
            } else {
                sql.append(line.substring(0, pos));
                execute(sql.toString(), conn);

                sql = new StringBuffer();
            }
        }
    }
    public static String[] getColumnNames(ResultSet rs) throws SQLException {
		ResultSetMetaData meta = rs.getMetaData();
		int cols = meta.getColumnCount();
		String[] columnNames = new String[cols];
		for (int i = 0; i < cols; i++) {
			columnNames[i] = meta.getColumnName(i + 1);
		}
		return columnNames;
	}
}
